// @ts-check
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './style.less'
import cs from 'classnames'
import { parseTimeReverse } from '../../utils'
import ScorllView from '../scorllView'
import useRequest from '../../api'
const EPSILON = 0.3


/** @type {React.FC<import('./type').LyricProps>}*/
const Lyric = ({
  containerClassName = '',
  currentTime = 0,
  style = {},
  offset = 0,
  musicId,
  highlightColor = '#66cc66'
}) => {
  // 获取歌词
  /** @type {import('../../types').UseRequestReturn<import('../lyric/type').Lyric>} */
  const [lyric, getLyric] = useRequest('/lyric')

  // 格式化lrc
  /** @type {[import('./type').LRC[], import('react').Dispatch<import('react').SetStateAction<import('./type').LRC[]>>]} */
  const [lrc, setLrc] = useState([])
  const lastHighlightIndex = useRef(0)

  // 切换歌曲重置
  useEffect(() => {
    lastHighlightIndex.current = 0
  }, [musicId])

  useEffect(() => {
    if(musicId) {
      getLyric({id: musicId})
    }
  }, [musicId])

  // 生成歌词列表
  useEffect(() => {
    if(lyric.data) {
      if(!lyric.data.nolyric) {
        if(lyric.data.lrc.lyric.length > 0) {
          const lrcList = lyric.data.lrc.lyric.split('\n')
          // 去掉空白
          lrcList.pop()
          const newLrc = lrcList.map(l => {
            const reg = /\[.*\]/gi
            const time = l.match(reg)[0].replace('[', '').replace(']','')
            const str = l.split(reg)[1]
            
            return ({
              // 有的歌曲是试听版
              time: parseTimeReverse(time) - offset,
              // 50个字换行
              str: str
            })
          })
          // console.log(newLrc)
          setLrc(newLrc)
        }
      } 
    }
  }, [lyric])

  // 高亮歌词
  const highlightIndex = useMemo(() => {
    if(lrc.length > 0) {
      // 双指针找最 近的两个
      let leftPointer = 0
      let leftDiff = 9999
      let rightPointer = 0 
      let rightDiff = -9999
      lrc.forEach((l, index) => {
        const diff = currentTime - l.time 
        if(diff > 0) {
          // 进度在歌词右侧（超过了歌词时间）
          if(leftDiff >= diff) {
            leftDiff = diff
            leftPointer = index
          }
        }else {
          // 进度在歌词左侧（还没有到歌词时间）
          if(rightDiff <= diff) {
            rightDiff = diff
            rightPointer = index
          }
        }
      })
      // 高亮进度右侧的那个
      return rightDiff >= -EPSILON ?  rightPointer :  leftPointer
    }
  }, [currentTime, lrc])

  return (
    <div 
      style = {style}
      className = {cs(styles['lyric'], containerClassName)}>
      {
        !lyric.loading ?
          <>
            {
              !lyric.data || !lyric?.data?.lrc?.lyric ?
                '暂无歌词' :
                lyric.data.nolyric ? 
                  '纯音乐，请您欣赏' 
                  :
                  <ScorllView className = { styles['scorll'] }>
                    {
                      lrc.map((l, index) => {
                        return <div 
                          key = {index} 
                          // transform: highlightIndex == index ? 'scale(1.2)' : ''
                          style = {{
                            color: highlightIndex == index ? highlightColor : '', 
                            ...(l.str.length >= 65 ? {fontSize: highlightIndex == index ? 'larger' : 'inherit'} : {transform: highlightIndex == index ? 'scale(1.2)' : ''}),
                          }}
                          className = {styles['item']}>{l.str}</div>
                      })
                    }
                  </ScorllView>
            }
          </>
          :
          <div>
            正在加载
          </div>
      }
    </div>
  )
}

export default Lyric
